//
//  PayViewController.swift
//  AutoPrint
//
//  Created by David on 2016/11/24.
//  Copyright © 2016年 fatcat. All rights reserved.
//

import UIKit

@objc protocol PayViewControllerDelegate {
    @objc optional func didFinishedPay(_ result: Bool)
}

class PayViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var delegate: PayViewControllerDelegate?
    
    override var preferredStatusBarStyle : UIStatusBarStyle {
        return .lightContent
    }
    
    fileprivate var amount:Double!
    
    convenience init(amount: Double){
        self.init()
        self.amount = amount
    }
    
    var statusLogo: UIImageView!
    var spinner: UIActivityIndicatorView!
    var statusToast: UIView!
    var statusLabel:UILabel!
    
    var tableView: UITableView!
    var navigationBar: UINavigationBar!
    
    var payMethod = 0
    
    var payBtn: UIButton!
    
    let ASK_BEFORE_EXIT_ALERT_ID = 344
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView = UITableView(frame: CGRect(x: 0, y: 64, width: view.bounds.width, height: view.bounds.height - 64), style: .grouped)
        view.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
        
        navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 64))
        view.addSubview(navigationBar)
        navigationBar.barStyle = .black
        navigationBar.tintColor = UIColor.white
        navigationBar.barTintColor = Fatcat.THEME_COLOR
        
        let navItem = UINavigationItem(title: "支付")
        navigationBar.pushItem(navItem, animated: true)
        navItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(PayViewController.close))
        
        
        payBtn = UIButton(frame: CGRect(x: 0, y: view.bounds.height - 48, width: view.bounds.width, height: 48))
        payBtn.setTitle("立即支付 ￥ \(amount)", for: UIControlState())
        payBtn.setTitleColor(UIColor.white, for: UIControlState())
        payBtn.backgroundColor = UIColor.orange
        payBtn.addTarget(self, action: #selector(PayViewController.handlePayment), for: .touchUpInside)
        view.addSubview(payBtn)
        
        statusToast = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        statusToast.backgroundColor = UIColor(white: 0, alpha: 0.7)
        statusToast.center = view.center
        statusToast.layer.cornerRadius = 8
        statusToast.alpha = 0
        view.addSubview(statusToast)
        
        spinner = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
        spinner.center = CGPoint(x: 50, y: 36)
        spinner.hidesWhenStopped = true
        statusToast.addSubview(spinner)
        
        statusLogo = UIImageView(image: UIImage(named: "warning"))
        statusLogo.center = CGPoint(x: 50, y: 36)
        statusToast.addSubview(statusLogo)
        
        statusLabel = UILabel(frame: CGRect(x: 0, y: 72, width: 100, height: 20))
        statusLabel.textColor = UIColor.white
        statusLabel.textAlignment = .center
        statusLabel.font = UIFont.systemFont(ofSize: 14)
        statusToast.addSubview(statusLabel)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Fatcat.payMethods.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "payMethod")
        let icon = UIImageView(frame: CGRect(x: 16, y: 8, width: 28, height: 28))
        cell.addSubview(icon)
        let nameLabel = UILabel(frame: CGRect(x: 52, y: 8, width: view.bounds.width - 80, height: 28))
        cell.addSubview(nameLabel)
        if Fatcat.payMethods[payMethod]["name"] == "alipay"{
            // MARK: 支付宝icon
            icon.image = UIImage(named: "alipay")
            nameLabel.text = "支付宝"
        }
        
        if indexPath.row == payMethod{
            cell.accessoryType = .checkmark
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 0{
            return "选择支付方式"
        }
        return nil
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        payMethod = indexPath.row
        tableView.reloadSections(IndexSet(integer: indexPath.section), with: .automatic)
    }
    
    func handlePayment(){
        statusToast.alpha = 1
        spinner.startAnimating()
        statusLabel.text = "请稍后"
        statusLogo.alpha = 0
        
        let amount = Int(self.amount*100)
        if amount != 0 {
            let postDic = NSMutableDictionary()
            postDic.setObject(String(amount), forKey: "amount" as NSCopying)
            postDic.setObject(Fatcat.payMethods[payMethod], forKey: "channel" as NSCopying)
            let postJson = try?  JSONSerialization.data(withJSONObject: postDic, options: .prettyPrinted)
            if postJson != nil {
                print(String(data: postJson!, encoding: .utf8) as Any)
            }
            
            /*
            if postJson != nil{
                print(NSString(data: postJson!, encoding: String.Encoding.utf8.rawValue))
                
                // MAR: 这只是ping++支付接口测试页面
                var resq = URLRequest(url: URL(string: "http://218.244.151.190/demo/charge")!)
                resq.httpMethod = "POST"
                resq.httpBody = postJson
                resq.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
                
                URLSession.shared.dataTask(with: resq, completionHandler: { (reData:Data?, resp:URLResponse?, err:Error?) in
                    if err == nil{
                        if let data = reData{
                            let charge = String(data: data, encoding: String.Encoding.utf8)
                            Pingpp.createPayment(charge, viewController: self, appURLScheme: "autoprint", withCompletion: { (res:String!, err:PingppError!) in
                                if err == nil{
                                    DispatchQueue.main.async(execute: {
                                        // MARK:支付成功
                                        //UIAlertView(title: res, message: nil, delegate: nil, cancelButtonTitle: "OK").show()
                                        self.statusLogo.image = UIImage(named: "tick")
                                        self.statusLogo.alpha = 1
                                        self.spinner.stopAnimating()
                                        self.statusLabel.text = "支付成功"
                                        UIView.animate(withDuration: 1, delay: 1, options: .curveLinear, animations: {
                                            self.statusLabel.alpha = 0
                                            }, completion: { (finished2) in
                                                self.delegate?.didFinishedPay?(true)
                                                self.dismiss(animated: true, completion: nil)
                                        })
                                        
                                        
                                    })
                                }else{
                                    DispatchQueue.main.async(execute: {
                                        self.statusLogo.image = UIImage(named: "warning")
                                        self.statusLogo.alpha = 1
                                        self.spinner.stopAnimating()
                                        self.statusLabel.text = "支付未成功"
                                        UIView.animate(withDuration: 0.5, delay: 2, options: .curveLinear, animations: { 
                                            self.statusToast.alpha = 0
                                            }, completion: nil)
                                    })
                                }
                            })
                        }
                    }
                }).resume()
            }else{
                print("json encode error")
            }
            */
        }
    }
    
    func close(){
        let alert = UIAlertController(title: "您还没支付", message: "你可以前往\"订单\"页面，在\(Fatcat.ORDER_UNPAY_EXPIRE_TIME)分钟内对此订单支付，否则自动退单", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "不退出", style: .cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "退出", style: .default, handler: { (action) in
            self.delegate?.didFinishedPay?(false)
            self.dismiss(animated: true, completion: nil)
        }))
        present(alert, animated: true, completion: nil)
        
    }
    
//    func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
//        if alertView.tag == ASK_BEFORE_EXIT_ALERT_ID{
//            if buttonIndex == 1{
//                delegate?.didFinishedPay?(false)
//                self.dismiss(animated: true, completion: nil)
//            }
//        }
//    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
